
class tsLoad {
  constructor(_this) {
    this._this = _this;
    this.dataType = _this.data.showCoachList ? '教练' : '驾校'; // 默认请求的内容
    this.snapshotExtra = null; // 附加筛选函数的快照
    this.initOptions();
  }
  initOptions() {
    this._this.data.teacherOptions = { // 请求老师列表的初始值
      areaId: '',
      cid: '',
      courseType: '',
      latitude: '',
      longitude: '',
      priceBegin: 0,
      descOrAsc: 'ASC',
      orderBy: 'DISTANCE', //排序SCORE-评分，SALES-销量，DISTANCE-距离
      priceEnd: 5000
    };
    this._this.data.schoolOptions = { // 请求学校列表的初始值
      areaId: '',
      cid: '',
      courseType: '',
      latitude: '',
      longitude: '',
      priceBegin: 0,
      priceEnd: 5000
    };
    this._this.data.teacherOptionsNext = { // 请求老师列表的初始值
      areaId: '',
      cid: '',
      courseType: '',
      latitude: '',
      longitude: '',
      priceBegin: 0,
      descOrAsc: 'ASC',
      orderBy: 'DISTANCE', //排序SCORE-评分，SALES-销量，DISTANCE-距离
      priceEnd: 5000
    };
    this._this.data.schoolOptionsNext = { // 请求学校列表的初始值
      areaId: '',
      cid: '',
      courseType: '',
      latitude: '',
      longitude: '',
      priceBegin: 0,
      priceEnd: 5000
    };
    const _location = getApp().globalData.userLocation;
    if (_location) {
      this._this.data.teacherOptions.latitude = _location.latitude;
      this._this.data.teacherOptions.longitude = _location.longitude;
      this._this.data.teacherOptionsNext.latitude = _location.latitude;
      this._this.data.teacherOptionsNext.longitude = _location.longitude;
      this._this.data.schoolOptions.latitude = _location.latitude;
      this._this.data.schoolOptions.longitude = _location.longitude;
      this._this.data.schoolOptionsNext.latitude = _location.latitude;
      this._this.data.schoolOptionsNext.longitude = _location.longitude;
    }
  }
  changeDataType(name) {
    this.dataType = name;
  }
  requestData() {
    // 先判断是否需要更新数据
    let canContinue = this.isNecessaryLoad();
    if (!canContinue) {
      return;
    }
    this.sendRequest();
  }
  sendRequest() {
    if (!getApp().globalData.userLocation) {
      return setTimeout(() => {
        this.sendRequest();
      }, 150)
    }
    if (this._this.data.requestTarget === '教练') {
      this.requestCoach();
    } else {
      this.requestSchool();
    }
  }
  isNecessaryLoad() { // 用来判断是否需要读取数据
    //// 为预防万一先写入地址
    const _location = getApp().globalData.userLocation;
    if(_location){
      this._this.data.teacherOptions.latitude = _location.latitude;
      this._this.data.teacherOptions.longitude = _location.longitude;
      this._this.data.teacherOptionsNext.latitude = _location.latitude;
      this._this.data.teacherOptionsNext.longitude = _location.longitude;
      this._this.data.schoolOptions.latitude = _location.latitude;
      this._this.data.schoolOptions.longitude = _location.longitude;
      this._this.data.schoolOptionsNext.latitude = _location.latitude;
      this._this.data.schoolOptionsNext.longitude = _location.longitude;
    }else{ 
      return false;
    }
    ///////////
    if (this._this.data.requestTarget !== this.dataType) { // 教练驾校切换
      this.initOptions();
      this.dataType = this._this.data.requestTarget;
      return true;
    }
    if (!this._this.data.jlList) { // 新数据
      return true;
    }
    // 判断是否修改排序，排序由于和筛选参数不会一起修改，所以可以分开判断处理下
    if (this._this.data.showCoachList) {
      if (this._this.data.teacherOptions.orderBy !== this._this.data.teacherOptionsNext.orderBy) {
        this._this.data.teacherOptions = Object.assign({}, this._this.data.teacherOptionsNext);
        return true;
      }
    } else {
      if (this._this.data.schoolOptions.orderBy !== this._this.data.schoolOptionsNext.orderBy) {
        this._this.data.schoolOptions = Object.assign({}, this._this.data.schoolOptionsNext);
        return true;
      }
    }
    // 判断是否修改了extraParams
    let nowState, nextState;
    if (this._this.data.showCoachList) {
      nowState = this._this.data.teacherOptions;
      nextState = this._this.data.teacherOptionsNext;
    } else {
      nowState = this._this.data.schoolOptions;
      nextState = this._this.data.schoolOptionsNext;
    }
    let testFlag = false;
    if( JSON.stringify(nowState) !== JSON.stringify(nextState) ){
      testFlag = true;
    }
    if (testFlag) {
      if (this._this.data.showCoachList) {
        this._this.data.teacherOptions = Object.assign({}, this._this.data.teacherOptionsNext);
      } else {
        this._this.data.schoolOptions = Object.assign({}, this._this.data.schoolOptionsNext);
      }
      return true;
    }
    return false;
  }
  requestCoach() { // 请求教练的数据
    wx.showLoading({});
    if (true) {
      this._this.setData({
        showCoachList: true,
        jlList: null,
      });
      if (this._this.data.teacherOptionsNext.orderBy === 'DISTANCE') {
        this._this.data.teacherOptionsNext.descOrAsc = "ASC"; // 距离为升序
        this._this.data.teacherOptions.descOrAsc = "ASC"; // 距离为升序
      } else {
        this._this.data.teacherOptionsNext.descOrAsc = "DESC"; // 评分和销量为降序
        this._this.data.teacherOptions.descOrAsc = "DESC"; // 评分和销量为降序
      }
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/listTeacher',
        method: 'GET',
        data: this._this.data.teacherOptions,
        header: {
          // Authorization: getApp().globalData.login.token,
        },
        success: (res) => {
          if (res.data.code == 0) {
            //// 去重，多班级带来的价格处理
            let filterArray = [];
            for (let i of res.data.data) {
              let elementExisted = false;
              for (let j of filterArray) {
                if (i.id === j.id) {
                  if (j.priceRange) {
                    if (i.pfPrice > j.priceRange[1]) {
                      j.priceRange[1] = i.pfPrice;
                    } else if (i.pfPrice < j.priceRange[0]) {
                      j.priceRange[0] = i.pfPrice;
                    }
                  } else {
                    j.priceRange = [];
                    if (i.pfPrice < j.pfPrice) {
                      j.priceRange.push(i.pfPrice);
                      j.priceRange.push(j.pfPrice);
                    } else {
                      j.priceRange.push(j.pfPrice);
                      j.priceRange.push(i.pfPrice);
                    }
                  }
                  elementExisted = true;
                }
              }
              if (!elementExisted) {
                filterArray.push(i);
              }
            }
            /////
            const _t = [];
            for (let i of filterArray) {
              let t = Object.assign({}, i); // 处理关键词
              if (i.mark && i.mark.length > 1) {
                t.special = (i.mark.split(',')).slice(0, 4);
              }
              let distance = parseFloat(i.distance);
              if (distance >= 1000) {
                t.distance = (distance / 1000).toFixed(1) + 'km';
              } else {
                t.distance = distance + 'm';
              }
              t.score ? t.score = t.score.toFixed(1) : t.score = '0.0';
              _t.push(t);
            };
            this._this.setData({
              jlList: _t,
              loadingJLDone: true,
            });
          }
        },
        fail:(err) => {
          wx.showModal({
            title: '网络请求错误',
            content: '读取数据失败，请检查网络',
            showCancel: false,
            confirmText: '关闭',
            confirmColor: '',
          })
        },
        complete: (d) => {
          wx.hideLoading();
        }
      })
    }
  }
  requestSchool() { // 请求驾校的数据
    wx.showLoading({});
    if (true) {
      this._this.setData({
        showCoachList: false,
        jlList: null,
      });
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/listSchool',
        method: 'GET',
        data: this._this.data.schoolOptions,
        header: {
          // Authorization: getApp().globalData.login.token,
        },
        success: (res) => {
          if (res.data.code == 0) {
            const _t = [];
            for (let i of res.data.data) {
              let t = Object.assign({}, i); // 处理关键词
              if (i.mark && i.mark.length > 1) {
                t.special = (i.mark.split(',')).slice(0, 4);
              }
              let distance = parseFloat(i.distance);
              if (distance >= 1000) {
                t.distance = (distance / 1000).toFixed(1) + 'km';
              } else {
                t.distance = distance + 'm';
              }
              t.score = !t.score ? '0.0' : t.score.toFixed(1);
              _t.push(t);
            };
            this._this.setData({
              jlList: _t,
              loadingJLDone: true,
            });
            const url = getApp().globalData.serverAddress;
            const token = getApp().globalData.login.token;
            // for (let i of this._this.data.jlList) {
            //   let _url = url + 'student/index/getSchoolEvaluateStatisticsVo?id=' + i.areaId;
            //   requestEvaOfSchool(this._this, _url, i.areaId, token);
            // }
          }
        },
        fail: (err) => {
          wx.showModal({
            title: '网络请求错误',
            content: '读取数据失败，请检查网络',
            showCancel: false,
            confirmText: '关闭',
            confirmColor: '',
          })
        },
        complete: (d) => {
          wx.hideLoading();
        }
      })
    }
  }
}

module.exports = tsLoad;

function requestEvaOfSchool(_this, url, id, token) {
  wx.request({
    url: url,
    data: '',
    header: {
      Authorization: token,
    },
    method: 'GET',
    success: function (res) {
      if (res.data.code === 0) {
        for (let i of _this.data.jlList) {
          if (i.areaId == id) {
            i.score = res.data.data.score.toFixed(1);
            _this.setData({
              jlList: _this.data.jlList,
            });
            break;
          }
        }
      }
    },
    fail: function (res) { },
    complete: function (res) { },
  })
}
